<?php
/***
* +----------------------------------------------------------------------+
* | DATE: 2008-4-22                                                      |
* +----------------------------------------------------------------------+
* | Author: YuYii <fin1983@Hotmail.com>                                  |
* +----------------------------------------------------------------------+
*/

$data = "[
		['03/15/2006',120,'交通费用','交通a',''],
		['03/15/2006',120,'交通费用','交通','ghgj']
    ];";


?>
<script language="javascript">
	
	/*
    var thedate = new myDatePicker({
        renderTo:"mydate",
        spDate: datainfo,
		hideMode:'offsets'
    }
    );
	thedate.hide();
	*/
	

	function rmbMoney(v) {
		v=(Math.round((v-0)*100))/100;
		v=(v==Math.floor(v))?v+".00":((v*10==Math.floor(v*10))?v+"0":v);
		v=String(v);var ps=v.split(".");
		var whole=ps[0];
		var sub=ps[1]?"."+ps[1]:".00";var r=/(\d+)(\d{3})/;
		while(r.test(whole)){whole=whole.replace(r,"$1"+","+"$2")}
		v=whole+sub;
		if(v.charAt(0)=="-"){return"-"+v.substr(1)}
		return v;
	}

    function change(val){
        if(val > 0){
            return '<span style="color:green;">' + val + '</span>';
        }else if(val < 0){
            return '<span style="color:red;">' + val + '</span>';
        }
        return val;
    }

    function pctChange(val){
        if(val > 0){
            return '<span style="color:green;">' + val + '%</span>';
        }else if(val < 0){
            return '<span style="color:red;">' + val + '%</span>';
        }
        return val;
    }

	var record = new Ext.data.Record.create([
		{name: 'dodate', type: 'date', dateFormat: 'm/d/Y'},
		{name: 'price', type: 'float'},
		{name: 'desc'},
		{name: 'type'},
		{name: 'remark'}
	]);

	var theDate = new Date().clearTime().format('Y-m-d'); //默认为今天


    // create the data store
    var store = new Ext.data.SimpleStore({
		url: 'actions/costs.php?action=getOut&from=' + theDate,
        fields: [
			{name: 'id'},
			{name: 'price', type: 'float'},
			{name: 'dodate', type: 'date', dateFormat: 'Y-m-d'},
			{name: 'type'},
			{name: 'desc'},
			{name: 'remark'}
        ]
    });
	//store.loadData(myData);
	store.load();

/*
Ext.grid.CheckColumn = function(config){
    Ext.apply(this, config);
    if(!this.id){
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype ={
    init : function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown : function(e, t){
        if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
            e.stopEvent();
            var index = this.grid.getView().findRowIndex(t);
            var record = this.grid.store.getAt(index);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
        }
    },

    renderer : function(v, p, record){
        p.css += ' x-grid3-check-col-td'; 
        return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
    }
};

	var checkColumn = new Ext.grid.CheckColumn({
       header: "选中",
       dataIndex: 'choose',
       width: 55
    });

*/


	//获取类别数据
	var belong_data = new Ext.data.SimpleStore({
		url: 'actions/types.php?action=getCostType&belong=out',
		fields: [
			{name:'id'},
			{name:'content'},
			{name:'desc'},
			{name:'type'}
		]
	});
	

    var belong = new Ext.form.ComboBox({
		store:belong_data,
		displayField:'content',    //显示项
		typeAhead: true,
		selectOnFocus:true,
		triggerAction: 'all', //点击ComboBox后触发获取数据的行为
		allowBlank:false,
		editable:false,
		emptyText:'Select ...'
	});
	// create the cm
	var cm = new Ext.grid.ColumnModel([
		//new Ext.grid.RowNumberer(),
		{header: "日期", width: 60, sortable: true, renderer: Ext.util.Format.dateRenderer('M d, Y'),locked:false, dataIndex: 'dodate',editor:new Ext.form.DateField({format:'M d, Y'})},
        {header: "金额", width: 60, sortable: true, renderer:rmbMoney ,dataIndex: 'price',
			editor: new Ext.form.NumberField({
               allowBlank: false,
               allowNegative: false,
               maxValue: 100000
           })},
        {header: "消费内容", width: 170,sortable: true, dataIndex: 'desc'},
        {header: "类别", width: 70, sortable: true, dataIndex: 'type',editor:belong},
		{header: "备注", sortable: true, dataIndex: 'remark',editor:new Ext.form.TextField()}
		//checkColumn
	]);

	var gridForm = new Ext.BasicForm(
			Ext.get("updategrid"),
			{}
		);


	//日期
    var datestore = new Ext.data.SimpleStore({
        url: 'actions/costs.php?action=getDateTips',
        fields: [
            {name: 'date'},
            {name: 'tips'}
        ]
    });


    //右上角按钮

    var win;
    var winheight = 230;
    var button_ev;
    if (window.ActiveXObject) {
        winheight = 241;
    }

    newWin = function() {
        var dateinfo = new Array();
        for(var i=0;i<datestore.getCount();i++) {
            var record = datestore.getAt(i);
            dateinfo[i] = record.data;
        }
            
        win = new Ext.Window({
            title:'选择日期',
            layout:'fit',
            width: 370,
            height:winheight,
            resizable:false,
            plain: true,
            items: new Ext.Panel({
                items:  new myDatePicker({
                    spDate: dateinfo,
                    cls:'x-date-inner-op',//元素渲染
                    ctCls: 'x-date-inner-op',//容器渲染
                    handler : function(dp, date){
                        Ext.MessageBox.alert('Date Selected', date.format('M j, Y'));
                        datewindow.hide();
                    }
                })
            })
        });
        win.on('beforehide',function(){win = '';});
        win.show(button_ev);
    }


    // create the Grid
    var grid = new Ext.grid.EditorGridPanel({
        store: store,
		renderTo:'costdata',
        cm: cm,
		sm:new Ext.grid.CheckboxSelectionModel(),	//(selModel) 提供选择行功能
		viewConfig: {forceFit:true},
        stripeRows: true,
        autoExpandColumn: 'desc',
        height:300,
		loadMask:true, 
		width:808,
		buttons:[
		{
			text:'保存',
			id:"save",
			handler: function() {
				jsonData = "[";
				
				for(i=0;i<store.getCount();i++) {
					record = store.getAt(i);
					//if(record.data.newRecord || record.dirty) {
						jsonData += Ext.util.JSON.encode(record.data) + ",";
					//}
				}
				
				jsonData = jsonData.substring(0,jsonData.length-1) + "]";
								
				gridForm.submit(
					{
						waitMsg:'操作中，请稍后......',
						method : "POST",
						url:'actions/costs.php?action=setOut',
						params:{'data':jsonData,'from':theDate,'to':theDate},
						success:function(form, action) {
							alert('Congrats!  Your changes were saved!!!!');
							store.load();
						},
						failure: function(form, action) {
							alert('Oops the delete did not work out too well!');
						}
					}
				);
			}
		}
		,{
			text:'重置',
			handler : function(){
				Ext.MessageBox.confirm('提示', 
						'是否确定重置数据内容？', 
						function(btn) {
							 if(btn == 'yes')
								store.load();
						}
				);
			}
		 }],
        //title:'Array Grid',
		tbar: [{
			text: '添加',
            iconCls:'add',
            handler : function(){
				var p = new record({
					dodate: (new Date()),
					desc: '',
					type: '娱乐',
					price: 0,
					remark:''
				});
				store.insert(0, p);
            }
		},
		{
			text: '删除',
            iconCls:'remove',
            handler : function(){
				m = grid.getSelections();
				if(m.length > 0)
				{
					for (i=0;i<m.length ;i++ )
					{
						store.remove(m[i]);
					}
				}
			}
		},
		{
			text: '日期:  ' + theDate,
			cls:'tbar_date',
			id: 'theDate_href'
		}
		]
    });
    var button = Ext.get('theDate_href');

	button.on('click', function(){
        if(!win){
            button_ev = this;
            datestore.on('load',newWin);
            datestore.load();
        }
    });

	

    //grid.render('costdata');
</script>

<div id="costdata"></div>
<form id="updategrid"></form>